package cn.ekuma.pos.pda.sale;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import cn.ekuma.epos.bean.util.sale.TicketHelper;
import cn.ekuma.epos.businesslogic.TicketUtil;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.epos.datalogic.I_DataLogicSales;

import com.openbravo.bean.AppUser;
import com.openbravo.bean.Customer;
import com.openbravo.bean.Location;
import com.openbravo.bean.Product;
import com.openbravo.bean.ProductScore;
import com.openbravo.bean.Tax;
import com.openbravo.bean.sales.Ticket;
import com.openbravo.bean.sales.TicketLine;
import com.openbravo.data.basic.BasicException;
import com.openbravo.pos.printer.AbstractTicketPrintManager;
import com.openbravo.pos.sales.TaxesLogic;

public class TicketManager {

	public static final int MSG_SUCCESS = 0;
    public static final int MSG_FAILURE = 1;
    public static final int MSG_NO_FIND_PRODUCT = 2;
    public static final int MSG_REFULSH_TICKET = 3;
    public static final int MSG_TICKETLINE_ADD = 4;
    public static final int MSG_TICKETLINE_REMOVE = 5;
    
	
	protected TaxesLogic taxeslogic;
	protected Ticket currentTicket;
	private boolean addtax;
	private AbstractTicketPrintManager printManager;
	protected AppUser appUser;
	//I_DataLogicSystem m_dlSystem;
	I_DataLogicSales dlSales;
	I_DataLogicReceipts dlreceipts;
	Context context;
	protected Handler mHandler;
	private Location locationId=new Location("0");
	private String priceGroup;
	private boolean isTmepTicket;
	private boolean isEditable;
	
	public TicketManager(Context context, Handler mHandler) {
		this.context = context;
		this.mHandler = mHandler;
		this.printManager=printManager;
	}

	
	public void init(){
		appUser=new AppUser();
		
		final ProgressDialog dialog = ProgressDialog.show(context, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				dlSales=DataLogicPDA.getDLSales();
				try {
					java.util.List<Tax> taxlist = dlSales.listWithClassName(Tax.class.getName());
					taxeslogic = new TaxesLogic(taxlist);
				} catch (BasicException e) {
					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
			}.start();
	}
	
	public boolean removeTicketLine(int i){
		//if (!RoleUtil.hasPermission(appUser, RoleUtil.Permission_EDIT_TICKET_LINE))
			//return false;
		System.out.println("移除了行："+i);
		if (currentTicket.getLine(i).isProductCom()) {
				// Es un producto auxiliar, lo borro y santas pascuas.
			currentTicket.removeLine(i);
			mHandler.obtainMessage(MSG_TICKETLINE_REMOVE,i).sendToTarget();
	  } else {
				TicketLine removeLine = currentTicket.getLine(i);
				// Es un producto normal, lo borro.
				currentTicket.removeLine(i);
				mHandler.obtainMessage(MSG_TICKETLINE_REMOVE,i).sendToTarget();
				// Y todos lo auxiliaries que hubiera debajo.
				while (i < currentTicket.getLinesCount()
						&& currentTicket.getLine(i).isProductCom()) {
					currentTicket.removeLine(i);
					mHandler.obtainMessage(MSG_TICKETLINE_REMOVE,i).sendToTarget();
				}
			}
		return true;	
	}
	
	
	public Ticket getCurrentTicket() {
		return currentTicket;
	}


	public void setCurrentTicket(Ticket currentTicket,boolean isEditable) {
		this.currentTicket = currentTicket;
		this.isEditable=isEditable;
	}


	public AppUser getAppUser() {
		return appUser;
	}


	public void setAppUser(AppUser appUser) {
		this.appUser = appUser;
	}


	public Location getLocationId() {
		return locationId;
	}


	public void setLocationId(Location locationId) {
		this.locationId = locationId;
	}


	public String getPriceGroup() {
		return priceGroup;
	}


	public void setPriceGroup(String priceGroup) {
		this.priceGroup = priceGroup;
	}


	public void addSelectedProduct(final HashMap<String,Double> maps){
		final ProgressDialog dialog = ProgressDialog.show(context, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				dlSales=DataLogicPDA.getDLSales();
				Product p=null;
				try {
				   for(Entry<String, Double> e:maps.entrySet()){
					  List<Product> tempList=dlSales.getProductInfoByCode(e.getKey());
					  if(tempList.size()>0){
						  p=tempList.get(0);
						  incProduct(e.getValue(),p);
					  }
				   }
				   if(p==null)
					   mHandler.obtainMessage(TicketManager.MSG_NO_FIND_PRODUCT).sendToTarget();//获取图片失败   
				} catch (BasicException e) {
					mHandler.obtainMessage(TicketManager.MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
			}.start();
	}
	
	public void addSelectedProduct(final Product obj){
		 final ProgressDialog dialog = ProgressDialog.show(context, "", 
			        "查旬中，请稍等 …", true, true);
			new Thread(){
				
				@Override
				public void run(){
					dlSales=DataLogicPDA.getDLSales();
					try {
						incProduct(1.0,obj);
					} catch (BasicException e) {
						e.printStackTrace();
						mHandler.obtainMessage(TicketManager.MSG_FAILURE).sendToTarget();//获取图片失败   
					}
					dialog.dismiss(); 
				}
				}.start();
	}
	
	
	public void addSelectedProduct(double price){
		addSelectedProduct(getInputProduct(price));
	}

	public void incProduct(double dPor, Product prod) throws BasicException {
		// precondicion: prod != null
		Customer customer = currentTicket.getCustomer();
		double salePrice = prod.getPriceSell();
		if (customer != null && prod.getM_dCustomerPrice() > 0) {
			salePrice = prod.getM_dCustomerPrice();
		}
		if(priceGroup!=null){
			try {
                salePrice=TicketUtil.getProductPrice(dlSales,customer,prod,priceGroup); 
			} catch (BasicException e) {
				return;
			}
		}
		addTicketLine(prod, dPor, salePrice);
}
	
	private void addTicketLine(Product oProduct, double dMul, double dPrice) throws BasicException {
		
		Tax tax = taxeslogic.getTaxInfo(oProduct.getTaxCategoryID(),currentTicket.getCustomer());
	
		 addTicketLine(new TicketLine(oProduct, dMul, dPrice, tax,
				(java.util.HashMap) (oProduct.getProperties().clone()),
				currentTicket.getM_dPriceRate()));
	}

	protected void addTicketLine(TicketLine oLine) throws BasicException{
	
	           TicketLine newAddLine=null;
				newAddLine = TicketUtil.addLine(dlSales,currentTicket,
							oLine,locationId);
				TicketUtil.checkTicketLineProductScore(dlSales, currentTicket, oLine, ProductScore.TYPE_Store,locationId);
				mHandler.obtainMessage(TicketManager.MSG_TICKETLINE_ADD,currentTicket.getLinesCount()).sendToTarget();
				// vista...
				if (newAddLine != null) {
					Tax tax = taxeslogic.getTaxInfo(
							newAddLine.getProductTaxCategoryID(),currentTicket.getCustomer());
					newAddLine.setTaxInfo(tax);
					//currentTicket.addLine(newAddLine);
					mHandler.obtainMessage(TicketManager.MSG_TICKETLINE_ADD,currentTicket.getLinesCount()).sendToTarget();
				}
	}
	
	
	
	private Product getInputProduct(double price) {
		Product oProduct = new Product(); // Es un ticket
		oProduct.setReference(null);
		oProduct.setCode(null);
		oProduct.setName("");
		//oProduct.setTaxCategoryID(((TaxCategory) taxcategoriesmodel.getSelectedItem()).getID());
		oProduct.setPriceSell(includeTaxes(oProduct.getTaxCategoryID(),price));
	
		return oProduct;
	}
	
	private double includeTaxes(String tcid, double dValue) {
		if (addtax) {
			Tax tax = taxeslogic.getTaxInfo(tcid, currentTicket.getCustomer());
			double dTaxRate = tax == null ? 0.0 : tax.getRate();
			return dValue / (1.0 + dTaxRate);
		} else {
			return dValue;
		}
	}
	

	public void changeCustomer(final Customer cu){
		final ProgressDialog dialog = ProgressDialog.show(context, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				try{
				  dlSales=DataLogicPDA.getDLSales();
				  TicketUtil.changeCustomer(dlSales, currentTicket, cu, priceGroup);
				  currentTicket.setCustomer(cu);
				  mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();//获取图片失败  
				} catch (BasicException e) {
				  mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
		}.run();
	}
	
	/**
	 * ------------------以下是单据管理类应用函数
	 */
	public void newTicket() {
		Date time=new Date();
		currentTicket=new Ticket();
		currentTicket.setKey(String.valueOf(time.getTime()));
		currentTicket.setLocation(locationId.getID());
		currentTicket.setHostName("pos-pda-sale");
		currentTicket.setUser(appUser.getUserInfo());
		isTmepTicket=true;
		isEditable=true;
	}
	
	public void clearCurrentTicket() {
		currentTicket.setLines(new ArrayList<TicketLine>());
	}

	public void saveCurrentTicket() {
		final ProgressDialog dialog = ProgressDialog.show(context, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				 dlreceipts=DataLogicPDA.getDLReceipts();
				try {
					if(isTmepTicket){
						dlreceipts.insertSharedTicketNoLock(currentTicket.getId(), currentTicket);
						isTmepTicket=false;
					}else
						dlreceipts.updateSharedTicketAndUnLocked(currentTicket.getId(), currentTicket);
				} catch (BasicException e) {
					mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
		}.start();
	}
	
	
	public void loadShardTicket(final String shardTicketId){
		final ProgressDialog dialog = ProgressDialog.show(context, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				 dlreceipts=DataLogicPDA.getDLReceipts();
				try {
					Ticket lists=dlreceipts.getSharedTicket(shardTicketId);
					if(lists!=null){
						currentTicket=lists;
						isEditable=true;
						mHandler.obtainMessage(MSG_SUCCESS,lists).sendToTarget();//获取图片失败   
					}
				} catch (BasicException e) {
					  mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败   
				}
				dialog.dismiss(); 
			}
			}.start();
	}


	public boolean isEditable() {
		return isEditable;
	}
	
	OnTicketChangedListener ticketChangeListener;
	
	public interface OnTicketChangedListener{
	       public void ticketChanger(TicketManager manager);
	}
	
	public void fireTicketChanged(){
		if(ticketChangeListener!=null)
			ticketChangeListener.ticketChanger(this);
	}
	
	public void setOnTicketChangedListener(OnTicketChangedListener l){
		this.ticketChangeListener=l;
	}
	
	public void removeOnTicketChangedListener(OnTicketChangedListener l){
		this.ticketChangeListener=null;
	}
	
	OnTicketStateChangedListener ticketStateChangeListener;
	public interface OnTicketStateChangedListener{
	       public void ticketStateChanger(TicketManager manager);
	}
	
	public void setOnTicketStateChangedListener(OnTicketStateChangedListener l){
		this.ticketStateChangeListener=l;
	}
	
	public void removeOnTicketStateChangedListener(){
		this.ticketStateChangeListener=null;
	}
	
	public void fireTicketStateChanged(){
		if(ticketStateChangeListener!=null)
			ticketStateChangeListener.ticketStateChanger(this);
	}
	
	
	public boolean payTicket(){
		return true;
	}


	public double getTotalPrice() {
		return TicketHelper.getTotal(getCurrentTicket());
	}
}
